package sms

import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/sirupsen/logrus"
)

const (
	/*-----------阿里短信平台------------*/
	AccessKeyID     = "LTAI5t6pney5ASXzzDeahHdy"
	AccessKeySecret = "ZXHGm3lgCBx2pJonYyeoq2zouwzwmY"
)

type Sms struct {
	PhoneNo       string
	SignName      string
	TemplateCode  string
	TemplateParam string
}

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func createClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		// 必填，您的 AccessKey ID
		AccessKeyId: accessKeyId,
		// 必填，您的 AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

func SmsAliSend(sms *Sms) (_err error) {
	logrus.Infof("发送短信验证码接口:%v", sms)
	// 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html
	client, _err := createClient(tea.String(AccessKeyID), tea.String(AccessKeySecret))
	if _err != nil {
		logrus.Errorf("发送短信验证码接口:%v err:%s", sms, _err)
		return _err
	}

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{}
	sendSmsRequest.PhoneNumbers = &sms.PhoneNo
	sendSmsRequest.SignName = &sms.SignName
	sendSmsRequest.TemplateCode = &sms.TemplateCode
	sendSmsRequest.TemplateParam = &sms.TemplateParam
	runtime := &util.RuntimeOptions{}
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		_, _err = client.SendSmsWithOptions(sendSmsRequest, runtime)
		if _err != nil {
			logrus.Errorf("发送短信验证码接口:%v err:%s", sms, _err)
			return _err
		}

		return nil
	}()

	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		// 如有需要，请打印 error
		_, _err = util.AssertAsString(error.Message)
		if _err != nil {
			logrus.Errorf("发送短信验证码接口:%v err:%s", sms, _err)
			return _err
		}
	}
	return _err
}

//
//func main() {
//	err := _main(tea.StringSlice(os.Args[1:]))
//	if err != nil {
//		panic(err)
//	}
//}
